<template>
  <div>
  <div style="width: 30%; float:left;">
    <el-input placeholder="输入关键字进行过滤"
              v-model="filterText">
    </el-input>
    <el-tree :data="treeData" default-expand-all :filter-node-method="filterNode"
             :expand-on-click-node=false node-key="id" ref="tree" highlight-current :props="defaultProps"
             @node-click="handleNodeClick">
    </el-tree>
  </div>
  <div style="width: 65%; float:left;">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleDelete" type="primary" icon="el-icon-edit">删除</el-button>
    </div>
    <el-table :key='tableKey' ref="multipleTable" :data="list" v-loading="listLoading"
              element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" label="序号" width="65">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="id" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="编码">
        <template slot-scope="scope">
          <span>{{scope.row.code}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{scope.row.type}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="办公地址">
        <template slot-scope="scope">
          <span>{{scope.row.officeSite}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="注册地址">
        <template slot-scope="scope">
          <span>{{scope.row.registrySite}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="法人代表">
        <template slot-scope="scope">
          <span>{{scope.row.legalRep}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="注册资本">
      <template slot-scope="scope">
        <span>{{scope.row.registryCapital}}</span>
      </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="联系电话">
        <template slot-scope="scope">
          <span>{{scope.row.corpTel}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="220" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="机构编码" prop="code">
          <el-input v-model="temp.code" placeholder="请输入机构编码"></el-input>
        </el-form-item>
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入机构名称"></el-input>
        </el-form-item>
        <el-form-item label="机构类型" prop="title">
          <el-input v-model="temp.type"></el-input>
        </el-form-item>
        <el-form-item label="办公地址" prop="description">
          <el-input v-model="temp.officeSite"></el-input>
        </el-form-item>
        <el-form-item label="注册地址" prop="orders">
          <el-input v-model="temp.registrySite"></el-input>
        </el-form-item>
        <el-form-item label="法人" prop="orders">
          <el-input v-model="temp.legalRep"></el-input>
        </el-form-item>
        <el-form-item label="注册资本" prop="orders">
          <el-input v-model="temp.registryCapital"></el-input>
        </el-form-item>
        <el-form-item label="联系电弧" prop="orders">
          <el-input v-model="temp.corpTel"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
  import { tree, list, create, update, deleted } from '@/api/sysorg'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'org',
    directives: {
      waves
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    data() {
      return {
        filterText: '',
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        tempTreeNodeData: {
          id: undefined,
          lable: '',
          children: undefined
        },
        treeSelectData: null,
        treeSelectId: 0,
        tableKey: 0,
        list: null,
        multipleSelection: [],
        listLoading: false,
        temp: {
          id: undefined,
          code: '',
          name: '',
          parent: undefined,
          type: 1,
          officeSite: '',
          registrySite: '',
          legalRep: '',
          registryCapital: undefined,
          corpTel: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          code: [{ required: true, message: '机构编码不能为空', trigger: 'change' }],
          name: [{ required: true, message: '机构名称不能为空', trigger: 'change' }],
          type: [{ required: true, message: '机构类型不能为空', trigger: 'change' }]
        },
        roleId: undefined
      }
    },
    created() {
      this.initTree()
      this.getTable()
    },
    methods: {
      initTree() {
        tree().then(response => {
          this.treeData = response.data
        })
      },
      getTreeRootData() {
        for (var i = 0; i < this.treeData.length; i++) {
          if (this.treeData[i].id === 0) return this.treeData[i]
        }
        return null
      },
      getTable() {
        this.listLoading = true
        list(this.treeSelectId).then(response => {
          this.list = response.data
          this.listLoading = false
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      handleNodeClick(data) {
        if (this.treeSelectId !== data.id) {
          this.treeSelectData = data
          this.treeSelectId = data.id
          this.getTable()
        }
      },
      appendChildNode(nodeData) {
        if (this.treeSelectData == null) this.treeSelectData = this.getTreeRootData()
        if (!this.treeSelectData.children) {
          this.$set(this.treeSelectData, 'children', [])
        }
        this.treeSelectData.children.push(nodeData)
      },
      removeChildNode(id) {
        if (this.treeSelectData == null) this.treeSelectData = this.getTreeRootData()
        const children = this.treeSelectData.children
        const index = children.findIndex(d => d.id === id)
        children.splice(index, 1)
      },
      modifyChildNode(nodeData) {
        if (this.treeSelectData == null) this.treeSelectData = this.getTreeRootData()
        const children = this.treeSelectData.children
        const index = children.findIndex(d => d.id === nodeData.id)
        children[index].label = nodeData.label
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          code: '',
          name: '',
          parent: this.treeSelectId,
          type: 1,
          officeSite: '',
          registrySite: '',
          legalRep: undefined,
          registryCapital: undefined,
          corpTel: undefined
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            create(this.temp).then(response => {
              this.temp = response.data
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              const newChild = { id: response.data.id, label: response.data.name, children: [] }
              this.appendChildNode(newChild)
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
           // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            update(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              const node = { id: this.temp.id, label: this.temp.name, children: [] }
              this.modifyChildNode(node)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete() {
//        this.removeChildNode(this.treeSelectData, 11)
        var ids = []
        this.multipleSelection.forEach(function(item, index, array) {
          ids.push(item.id)
        })
        deleted(ids).then(response => {
          if (response.code==0) {
            for (var i = 0; i < ids.length; i++) {
              this.removeChildNode(ids[i])
              this.removeList(ids[i])
            }

            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      removeList(id) {
        const index = this.list.findIndex(d => d.id === id)
        this.list.splice(index, 1)
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style scoped>

</style>
